﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

public class DataManager : MonoBehaviour,IGameManager {

    public ManagerStatus status { get; private set; }

    private string _filename;

    private NetworkService _network;

    public void Startup(NetworkService service)
    {
        Debug.Log("Data manager starting...");

        _network = service;

        //构建game.dat文件的完整路径
        _filename = Path.Combine(Application.persistentDataPath, "game.dat");

        status = ManagerStatus.Started;
    }

    public void SaveGameState()
    {
        //序列化字典
        Dictionary<string,object> gamestate = new Dictionary<string, object>();
        gamestate.Add("inventory",Manager.Inventory.GetData());
        gamestate.Add("health",Manager.Player.health);
        gamestate.Add("maxHealth",Manager.Player.maxHealth);
        gamestate.Add("curLevel",Manager.Mission.curLevel);
        gamestate.Add("maxLevel",Manager.Mission.maxLevel);

        //在文件路径创建一个文件
        FileStream stream = File.Create(_filename);
        BinaryFormatter formatter = new BinaryFormatter();
        //序列化字典作为创建的文件的内容
        formatter.Serialize(stream,gamestate);
        stream.Close();
    }

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    public void LoadGameState()
    {
        //当只有文件存在时才继续加载
        if (!File.Exists(_filename))
        {
            Debug.Log("No saved game");
            return;
        }

        //用于放置加载数据的字典
        Dictionary<string, object> gamestate;

        BinaryFormatter formatter = new BinaryFormatter();
        FileStream stream = File.Open(_filename, FileMode.Open);
        gamestate = formatter.Deserialize(stream) as Dictionary<string, object>;
        stream.Close();

        //使用反序列化的数据更新管理器
        Manager.Inventory.UpdateData((Dictionary<string, int>) gamestate["inventory"]);
        Manager.Player.UpdateData((int) gamestate["health"], (int) gamestate["maxHealth"]);
        Manager.Mission.UpdateData((int) gamestate["curLevel"], (int) gamestate["maxLevel"]);
        Manager.Mission.RestartCurrent();
    }
}
